<?php
/**
 * Created by PhpStorm
 * Author: Rocky
 * DateTime: 2021-11-20 15:07
 */

$config = [
    'host' => '192.168.31.196',
    'port' => 5672,
    'vhost' => 'test_virtual',
    'login' => 'test',
    'password' => '123456'
];

// 连接broker
$connection = new AMQPConnection($config);
if (!$connection->connect()) {
    die('连接失败！');
}

// 创建通道
$channel = new AMQPChannel($connection);
// 创建交换机
$exchange = new AMQPExchange($channel);
// 声明交换机名称
$exchangeName = 'exchange_order';
// 设置交换机名称
$exchange->setName($exchangeName);
// 设置交换机类型
$exchange->setType(AMQP_EX_TYPE_DIRECT);
// 设置交换机属性：持久化
$exchange->setFlags(AMQP_DURABLE);
// 交换机声明
$exchange->declareExchange();

// 声明路由键
$routingKey = 'key_order';

// 创建队列
$queue = new AMQPQueue($channel);
// 声明队列名称
$queueName = 'queue_order';
// 设置队列名称
$queue->setName($queueName);
// 设置队列持久化
$queue->setFlags(AMQP_DURABLE);
// 队列声明
$queue->declareQueue();

// 声明路由键
$routingKey = 'key_order';
// 设置队列绑定交换机和路由键
$queue->bind($exchange->getName(), $routingKey);

// 生产消息
for ($i = 0; $i < 10000; $i++) {
    $msg = [
        'message_id' => date('mdHis_') . $i,
        'goods_id' => '10000' . $i,
        'goods_num' => mt_rand(1, 5),
        'user_id' => mt_rand(100000, 999999),
        'coupon_id' => mt_rand(0, 10000),
        'user_mobile' => mt_rand(13000000000, 13999999999)
    ];
    // delivery_mode=2，持久的队列+持久的消息在rabbitmq重启时才不会丢失
    $tmpResult = $exchange->publish(json_encode($msg), $routingKey, AMQP_NOPARAM, ['delivery_mode' => AMQP_DURABLE]);
    echo 'Send Message: ' . $tmpResult . PHP_EOL;
}

$channel->close();
$connection->disconnect();